package Command;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import Control.ICommandExecutor;

public class Move implements ICommandExecutor {
	private Move(){}
	private static Move instance;
	public static ICommandExecutor getInstance()
	{
		if (instance == null)
		{
			instance = new Move();
		}
		return instance;
	}
	public void execute(String command) {
		String[] cmd = command.split(" ");
		try {
			moveFile(cmd[1],cmd[2], cmd[3]);
		} catch (IOException e) {
			System.out.println("Error: "+e);
		}
	}
	
	private void readAndWriteStream(File input,File out) throws IOException
	{
		byte[] buf = new byte[1024]; 
		int countByte;
		InputStream readStream = new FileInputStream(input);
		FileOutputStream outStream = new FileOutputStream(out);
		while(true)
		{
			countByte = readStream.read(buf);
			if (countByte<=0)
				break;
			outStream.write(buf);
		}
		readStream.close();
		outStream.close();
	}
	
	private void moveFile(String fromDir, String fileName, String toDir) throws IOException
	{
		if (new File(fromDir+"\\"+fileName).exists() && new File(fromDir+"\\"+fileName).isFile())
		{
			if ((new File(toDir).exists()) && new File(toDir).isDirectory())
			{
				File readFile = new File(fromDir+"\\"+fileName);
				File createFile = new File(toDir+"\\"+fileName);
				createFile.createNewFile();
				readAndWriteStream(readFile,createFile);
				readFile.delete();
				System.out.println("File is move!");
			}
			else
				System.out.println("Dir not found!");
		}
		else 
			System.out.println("Movefile not found!");
	}

}
